<template>
	<view class="uni-tab-bar">
		<scroll-view id="tab-bar" class="uni-swiper-tab" scroll-x :scroll-left="scrollLeft">
			<view v-for="(tab,index) in tabBars" :key="tab.number" class="swiper-tab-list" :class="tabIndex==index ? 'active' : ''"
			 :id="tab.number" :data-current="index" @click="tapTab">{{tab.name}}<uni-badge v-if="tab.showcounttotal == 1" :text="tab.counttotal" type="error" /></view>
		</scroll-view>
		<swiper :current="tabIndex" class="swiper-box" :duration="300" @change="changeTab">
			<swiper-item v-for="(tab,index1) in newsitems" :key="index1">
				<scroll-view class="list" scroll-y @scrolltolower="loadMore(index1)">
					 <block v-for="(newsitem,index2) in tab.data" :key="index2">
					    <view class="uni-list-cell" hover-class="uni-list-cell-hover" @click="goDetail(newsitem)">
					        <view class="uni-triplex-row">
					            <view class="uni-triplex-left">
					                <text class="uni-title uni-ellipsis">{{newsitem.doctitle}}</text>
					                <text class="uni-text">列表副标题</text>
					                <text class="uni-text-small uni-ellipsis">列表内容文字,列表内容文字,列表内容文字,列表内容文字,列表内容文字,列表内容文字</text>
					            </view>
					            <view class="uni-triplex-right">
					                <text class="uni-h5"></text>
					            </view>
					        </view>
					    </view>
					</block>
					<view class="uni-tab-bar-loading">
						{{tab.loadingText}}
					</view>
				</scroll-view>
			</swiper-item>
		</swiper>
	</view>
</template>
<script>
	import uniBadge from '@/components/uni-badge/uni-badge.vue';
	
	const tpl = {
		data0: {
			"datetime": "40分钟前",
			"article_type": 0,
			"title": "uni-app行业峰会频频亮相，开发者反响热烈!",
			"source": "DCloud",
			"comment_count": 639
		},
		data1: {
			"datetime": "一天前",
			"article_type": 1,
			"title": "DCloud完成B2轮融资，uni-app震撼发布!",
			"image_url": "https://img-cdn-qiniu.dcloud.net.cn/uniapp/images/shuijiao.jpg?imageView2/3/w/200/h/100/q/90",
			"source": "DCloud",
			"comment_count": 11395
		},
		data2: {
			"datetime": "一天前",
			"article_type": 2,
			"title": "中国技术界小奇迹：HBuilder开发者突破200万",
			"image_url": "https://img-cdn-qiniu.dcloud.net.cn/uniapp/images/muwu.jpg?imageView2/3/w/200/h/100/q/90",
			"source": "DCloud",
			"comment_count": 11395
		},
		data3: {
			"article_type": 3,
			"image_list": [{
				"url": "https://img-cdn-qiniu.dcloud.net.cn/uniapp/images/cbd.jpg?imageView2/3/w/200/h/100/q/90",
				"width": 563,
				"height": 316
			}, {
				"url": "https://img-cdn-qiniu.dcloud.net.cn/uniapp/images/muwu.jpg?imageView2/3/w/200/h/100/q/90",
				"width": 641,
				"height": 360
			}, {
				"url": "https://img-cdn-qiniu.dcloud.net.cn/uniapp/images/shuijiao.jpg?imageView2/3/w/200/h/100/q/90",
				"width": 640,
				"height": 360
			}],
			"datetime": "5分钟前",
			"title": "uni-app 支持使用 npm 安装第三方包，生态更趋丰富",
			"source": "DCloud",
			"comment_count": 11
		},
		data4: {
			"datetime": "2小时前",
			"article_type": 4,
			"title": "uni-app 支持原生小程序自定义组件，更开放、更自由",
			"image_url": "https://img-cdn-qiniu.dcloud.net.cn/uniapp/images/cbd.jpg?imageView2/3/w/200/h/100/q/90",
			"source": "DCloud",
			"comment_count": 69
		}
	};

	export default {
		components: {
			uniBadge
		},
		data() {
			return {
				showRigth: false,
				scrollLeft: 0,
				isClickChange: false,
				tabIndex: 0,
				newsitems: [],
				tabBars: [{
					name: '关注',
					id: 'guanzhu'
				}, {
					name: '推荐',
					id: 'tuijian'
				}, {
					name: '体育',
					id: 'tiyu'
				}, {
					name: '热点',
					id: 'redian'
				}],
				
				baseUrl: 'https://easy-mock.com/mock/5c7fd5418cfae820245a9ab0/moa',
				groupJSONUrl: ''//获取二级菜单的相对url，exp:/MobilePortal.nsf/GetGroupListinfo?openagent&group=待办工作
			}
		},
		onLoad(option) {
			this.newsitems = this.randomfn();
			this.groupJSONUrl = '/MobilePortal.nsf/GetGroupListinfo?openagent&group=待办工作';//option;
			
		},
		methods: {
			goDetail(e) {
				uni.navigateTo({
					url: '/pages/template/tabbar/detail/detail?title=' + e.title
				});
			},
			close(index1, index2) {
				uni.showModal({
					content: '是否删除本条信息？',
					success: (res) => {
						if (res.confirm) {
							this.newsitems[index1].data.splice(index2, 1);
						}
					}
				})
			},
			loadMore(e) {
				setTimeout(() => {
					this.addData(e);
				}, 1200);
			},
			addData(e) {
				if (this.newsitems[e].data.length > 30) {
					this.newsitems[e].loadingText = '没有更多了';
					return;
				}
				
				
				for (let i = 1; i <= 10; i++) {
					this.newsitems[e].data.push(tpl['data' + Math.floor(Math.random() * 5)]);
				}
			},
			async changeTab(e) {
				console.log("change tab");
				let index = e.target.current;
				if (this.newsitems[index].data.length === 0) {
					this.addData(index)
				}
				if (this.isClickChange) {
					this.tabIndex = index;
					this.isClickChange = false;
					return;
				}
				let tabBar = await this.getElSize("tab-bar"),
					tabBarScrollLeft = tabBar.scrollLeft;
				let width = 0;

				for (let i = 0; i < index; i++) {
					let result = await this.getElSize(this.tabBars[i].id);
					width += result.width;
				}
				let winWidth = uni.getSystemInfoSync().windowWidth,
					nowElement = await this.getElSize(this.tabBars[index].id),
					nowWidth = nowElement.width;
				if (width + nowWidth - tabBarScrollLeft > winWidth) {
					this.scrollLeft = width + nowWidth - winWidth;
				}
				if (width < tabBarScrollLeft) {
					this.scrollLeft = width;
				}
				this.isClickChange = false;
				this.tabIndex = index; //一旦访问data就会出问题
			},
			getElSize(id) { //得到元素的size
				return new Promise((res, rej) => {
					uni.createSelectorQuery().select("#" + id).fields({
						size: true,
						scrollOffset: true
					}, (data) => {
						res(data);
					}).exec();
				})
			},
			async tapTab(e) { //点击tab-bar
				let tabIndex = e.target.dataset.current;
				if (this.newsitems[tabIndex].data.length === 0) {
					this.addData(tabIndex)
				}
				if (this.tabIndex === tabIndex) {
					return false;
				} else {
					let tabBar = await this.getElSize("tab-bar"),
						tabBarScrollLeft = tabBar.scrollLeft; //点击的时候记录并设置scrollLeft
					this.scrollLeft = tabBarScrollLeft;
					this.isClickChange = true;
					this.tabIndex = tabIndex;
				}
			},
			randomfn() {
				let ary = [];
				for (let i = 0, length = this.tabBars.length; i < length; i++) {
					let aryItem = {
						loadingText: '加载更多...',
						data: []
					};
					if (i < 1) {
						for (let j = 1; j <= 10; j++) {
							aryItem.data.push(tpl['data' + Math.floor(Math.random() * 5)]);
						}
					}
					ary.push(aryItem);
				}
				return ary;
			},
			getTabBarGroupData() {
				
				uni.showLoading({
					title: '请稍候，数据加载中...',
					mask: true
				});
				
				let url = this.baseUrl + this.groupJSONUrl;
				uni.request({
					url: url,
					success: (res) => {
						if (service.getServerResponseErr(res.data) == 0) {
							let jsonData = res.data;
							//console.log( JSON.stringify(jsonData));
							if (jsonData.tablist) {
								let i = 0;
								for (; i < jsonData.tablist.length; i++) {
									this.tabBars.push(jsonData.tablist[i]);
									
									let aryItem = {
										loadingText: '加载更多...',
										data: []
									};								
									this.newsitems.push(aryItem);
								}	
								if (i > 0)	this.getDoclistByGroupItem(jsonData.tablist[0].actioninfo.jsonurl, );
							}
						}
					},
					fail: (res) => {
						uni.hideLoading();
						uni.showToast({
							title:res.errMsg
						})
					}
				})	
			},
			getDoclistByGroupItem(doclistUrl, docunid, recno, moretype, keyword) {
				
				let url = this.baseUrl + doclistUrl;
				uni.request({
					url: url,
					data:{
						docunid: docunid,
						recno: recno,
						moretype: moretype,
						keyword: keyword
					},
					success: (res) => {
						if (service.getServerResponseErr(res.data) == 0) {
							let jsonData = res.data;
							//console.log( JSON.stringify(jsonData));
						
							if (moretype == 'all') {//全部
								
								this.newsitems[this.tabIndex].data = jsonData.doclist;
								
							}else if (recno > 0) {//下一页
								
								this.newsitems[this.tabIndex].data.push(jsonData.doclist);
								
							}else {//刷新回到首页
								
								this.newsitems[this.tabIndex].data = jsonData.doclist;
							}
						
							uni.hideLoading();
						}
					},
					fail: (res) => {
						uni.hideLoading();
						uni.showToast({
							title:res.errMsg
						})
					}
				})	
				
			}
			
		}
	}
</script>

<style>
	.uni-tab-bar-loading {
		text-align: center;
		font-size: 28upx;
		color: #999;
	}
</style>
